import {updateUser, login as serverLogin} from '@/api/userApi.js'
import Store from '@/store/index.js'

const getUserProfile = ()=>{
	return new Promise((resolve, reject)=>{
		uni.getUserProfile({
			desc: "获取用户信息",
			success(res) {
				resolve(res)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}
const wxLogin = ()=>{
	return new Promise((resolve, reject)=>{
		uni.login({
			success(res) {
				resolve(res.code)
			},
			fail(err) {
				reject(err)
			}
		})
	})
}

export const syncUserInfo = async ()=>{
	const profile = await getUserProfile()
	const response = await updateUser({
		rawData: profile.rawData,
		signature: profile.signature,
		encryptedData: profile.encryptedData,
		iv: profile.iv
	})
	
	Store.commit('setUserInfo', {
		nickname: profile.userInfo.nickName,
		headimgurl: profile.userInfo.avatarUrl,
		unionId: response.unionid
	})
}

export const login = async ()=>{
	const code = await wxLogin()
	const response = await serverLogin({code})
	
	Store.commit('setOpenid', response.openid)
	Store.commit('setScore', {score: response.score, recentTime: response.recentTime})
	if(!!response.user){
		Store.commit('setUserInfo', {
			nickname: response.user.nickname,
			headimgurl: response.user.avatarUrl,
			unionId: response.user.unionid
		})
	}
}

export const checkUpdate = ()=>{
  if(wx.canIUse('getUpdateManager')){
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate((res)=>{
      if(res.hasUpdate){
        updateManager.onUpdateReady(()=>{
          wx.showModal({
            title: '发现先版本',
            content: '新版本已经准备好，是否重启应用？',
            showCancel: false,
            success(res){
              if(res.confirm){
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })
  }
}

export const reportEvent = (name, params={})=>{
	uni.reportEvent(name, params)
}